package cn.rulian.base.curd.controller;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.rulian.base.common.dto.CommonDto;
import cn.rulian.base.common.dto.Message;
import cn.rulian.base.common.util.xx;
import cn.rulian.base.common.vo.Result;
import cn.rulian.base.curd.bo.Curd;
import cn.rulian.base.curd.bo.CurdField;
import cn.rulian.base.curd.dao.CurdFieldDao;
import cn.rulian.base.curd.service.CurdService;
import cn.rulian.base.curd.vo.CurdVo;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

/**
 * 代码生成 Controller
 */

@Controller
@RequestMapping("/base/curd/curd")
public class CurdController {
	
	@Autowired
	private CurdService service;
	
	@Autowired
	private CurdFieldDao curdFieldDao;
	
	private final String path="base/curd/curd_"; //页面基本路径

	/**
	 * 页面基本路径
	 */
	private String getPath()
	{
		return path;
	}
	
	/**
	 * 列表页面
	 */
	@RequestMapping("/listPage")
	public String listPage() {
		return this.getPath()+"list";
	}

	/**
	 * 查询
	 */
	@RequestMapping("/listData")
	@ResponseBody
	public Result listData(CurdVo vo) {
		return service.query(vo);
	}

	/**
	 * 增加页面
	 */
	@RequestMapping("/addPage")
	public String addPage() {
		return this.getPath()+"add";
	}

	/**
	 * 增加
	 */
	@RequestMapping("/add")
	@ResponseBody
	public Message add(CurdVo vo) {
		Message rm = new Message();
		Curd bo = vo.getObj();
		bo.setValidated(false);
		bo.setBuildConfig(false);
		bo.setConfig(false);
		bo.setConfigField(false);
		bo.setDefaultOrderType("asc");
		bo.setAddTime(new Date());
		try {
			service.save(bo);
			rm.setMsg("保存成功！");
			rm.setCode(Message._SUCCESS);
		} catch (Exception e) {
			rm.setMsg("保存失败，异常信息：<br/>" + e.toString());
			rm.setCode(Message._ERROR);
			e.printStackTrace();
		}
		return rm;
	}

	/**
	 * 修改页面
	 */
	@RequestMapping("/updatePage")
	public String updatePage(Model model, Long id) {
		model.addAttribute("bo", service.findOne(id));
		return this.getPath()+"update";
	}

	/**
	 * 修改
	 */
	@RequestMapping("/update")
	@ResponseBody
	public Message update(CurdVo vo,Long id) {
		Message rm = new Message();
		try {
			Curd obj = vo.getObj();
			Curd bo = service.findOne(id);
			bo.setCode(obj.getCode());
			bo.setName(obj.getName());
			bo.setBoPath(obj.getBoPath());
			bo.setRemark(obj.getRemark());
			service.save(bo);
			
			rm.setMsg("保存成功！");
			rm.setCode(Message._SUCCESS);
		} catch (Exception e) {
			rm.setMsg("保存失败，异常信息：<br/>" + e.toString());
			rm.setCode(Message._ERROR);
			e.printStackTrace();
		}
		return rm;
	}

	/**
	 * 删除
	 */
	@RequestMapping("/delete")
	@ResponseBody
	public Message delete(Long ids[]) {
		Message rm = new Message();
		try {
			for(Long id:ids)
			{
				Curd curd = service.findOne(id);
				if(curd.getUrlTest() != null)
				{
					rm.setMsg("请先【删除测试代码】！<br/><br/>说明：避免以后手动删除的麻烦。");
					rm.setCode(Message._ERROR);
					return rm;
				}
				curdFieldDao.delete(curdFieldDao.findByCurd_IdOrderBySn(id)); //删除子配置
				service.delete(id);
			}
			
			rm.setMsg("删除成功！");
			rm.setCode(Message._SUCCESS);
		} catch (Exception e) {
			rm.setMsg("删除失败，异常信息：<br/>" + e.toString());
			rm.setCode(Message._ERROR);
			e.printStackTrace();
		}
		return rm;
	}
	
	/**
	 * 详情页面
	 */
	@RequestMapping("/detailPage")
	public String detailPage(Model model, Long id) {
		model.addAttribute("bo", service.findOne(id));
		return this.getPath()+"detail";
	}
	
	/**
	 * 验证BO
	 */
	@RequestMapping("/validateBo")
	public String validateBo(Model model, Long id) {
		model.addAttribute("msg", service.validateBo(id));
		return this.getPath()+"info";
	}

	/**
	 * 生成默认配置
	 */
	@RequestMapping("/mackConfig")
	public String mackConfig(Model model, Long id) {
		try
		{
			model.addAttribute("msg", service.mackConfig(id));
		}
		catch (Exception e)
		{
			Message rm = new Message();
			rm.setCode(Message._ERROR);
			rm.setMsg("操作出错!!!" );
			rm.setOther("异常信息：<br/>" + e.toString());
			e.printStackTrace();
		}
		return this.getPath()+"info";
	}
	
	/**
	 * 主配置页面
	 */
	@RequestMapping("/mainConfigPage")
	public String mainConfigPage(Model model, Long id) {
		model.addAttribute("bo", service.findOne(id));
		return this.getPath()+"mainConfig";
	}

	/**
	 * 主配置更新
	 */
	@RequestMapping("/mainConfig")
	@ResponseBody
	public Message mainConfig(CurdVo vo,Long id,Boolean windowSizeAuto) {
		Message rm = new Message();
		try {
			Curd obj = vo.getObj();
			Curd bo = service.findOne(id);
			bo.setDefaultOrderFieldName(obj.getDefaultOrderFieldName());
			bo.setDefaultOrderType(obj.getDefaultOrderType());
			bo.setTdNum(obj.getTdNum());
			
			if(windowSizeAuto!=null && windowSizeAuto)
			{
				service.windowSizeAuto(bo);
			}
			else
			{
				bo.setWindowSize_add(obj.getWindowSize_add());
				bo.setWindowSize_update(obj.getWindowSize_update());
				bo.setWindowSize_detail(obj.getWindowSize_detail());
			}
			
			bo.setConfig(true);
			service.save(bo);
			
			rm.setMsg("保存成功！");
			rm.setCode(Message._SUCCESS);
		} catch (Exception e) {
			rm.setMsg("保存失败，异常信息：<br/>" + e.toString());
			rm.setCode(Message._ERROR);
			e.printStackTrace();
		}
		return rm;
	}
	
	/**
	 * 根据主配置ID,获取bo的所有属性信息。<br/>
	 * 用于主配置时下拉列表数据。
	 */
	@RequestMapping("/getFieldList")
	@ResponseBody
	public List<CommonDto> getFieldList(Long id)
	{
		return service.getFieldList(id);
	}
	

	
	/**
	 * 子配置页面
	 */
	@RequestMapping("/sonConfigPage")
	public String sonConfigPage(Model model, Long id) {
		model.addAttribute("curd", service.findOne(id));
		return this.getPath()+"sonConfig";
	}
	

	/**
	 * 子配置更新
	 */
	@RequestMapping("/sonConfig")
	@ResponseBody
	public Message sonConfig(Long id,String arrStr) {
		Message rm = new Message();
		try {
			//转换配置明细
			Gson gson = xx.getGson();
			List<CurdField> list = new ArrayList<>();
			list = gson.fromJson(arrStr, new TypeToken<List<CurdField>>() {}.getType());
			
			//列表按sn排序
     	    Collections.sort(list, new Comparator<CurdField>() {
	   			@Override
	   			public int compare(CurdField obj1, CurdField obj2) 
	   			{
	   				if(obj1.getSn() == null)
	   				{
	   					return -1;
	   				}
	   				return obj1.getSn().compareTo(obj2.getSn());
	   			}
	   		});
			
     	    //属性类型
			String type_String ="java.lang.String";
			String type_Boolean ="java.lang.Boolean";
			//String type_Integer ="java.lang.Integer";
			//String type_Byte ="java.lang.Byte";
			//String type_Short ="java.lang.Short";
			//String type_Long ="java.lang.Long";
			//String type_Double ="java.lang.Double";
			//String type_Float ="java.lang.Float";
			//String type_Date ="java.util.Date";
			
			//录入组件类型
			//String addType_00 = "00"; //默认 
			//String addType_S01 = "S01"; //文本-文本框
     	    //String addType_S02 = "S02"; //文本-文本区域
     	    String addType_S11 = "S11"; //文本-下拉框-固定序列
     	    String addType_S12 = "S12"; //文本-下拉框-URL
     	    String addType_S21 = "S21"; //文本-下拉框多选-固定序列
     	    String addType_S22 = "S22"; //文本-下拉框多选-URL
     	    
     	   //String addType_I01 = "I01"; //整数-录入
     	   //String addType_I02 = "I02"; //整数-微调
     	   //String addType_D01 = "D01"; //实数-录入
     	   //String addType_B01 = "B01"; //布尔-开关
     	   //String addType_DT01 = "DT01"; //日期-选择
     	   //String addType_DT02 = "DT02"; //日期-微调
     	   //String addType_DT03 = "DT03"; //时间-选择
     	   //String addType_DT04 = "DT04"; //时间-微调
     	   //String addType_T01 = "T01"; //类型-下拉选择
     	   //String addType_T02 = "T02"; //类型-下拉列表
			
			//校验
			for(CurdField f:list)
			{
				String fieldType = f.getFieldType();
				String addType = f.getAddType();
				String addSelectUrl = f.getAddSelectUrl(); //增加时：下拉数据URL
				String parameter = f.getParameter(); //参数：String：固定序列、String：URL取值属性、其他bo：URL显示属性、Boolean：true显示值
				
				//S12,S22：必须填写‘下拉URL’
				if(type_String.equals(fieldType) && (addType_S12.equals(addType) || addType_S22.equals(addType)))
				{
					if(addSelectUrl == null || "".equals(addSelectUrl.trim()))
					{
						rm.setCode(Message._ERROR);
						rm.setMsg("属性："+ f.getFieldName() +" 必须填写‘下拉URL’");
						return rm;
					}
				}
				
				//S11,S12,S21,S22：必须填写‘参数’
				if(type_String.equals(fieldType) && (addType_S11.equals(addType) || addType_S12.equals(addType) || addType_S21.equals(addType) || addType_S22.equals(addType))) 
				{
					if(parameter == null || "".equals(parameter.trim()))
					{
						rm.setCode(Message._ERROR);
						rm.setMsg("属性："+ f.getFieldName() +" 必须填写‘参数’");
						return rm;
					}
				}
			}
			
			Curd curd = service.findOne(id);
			boolean haveSumTitle = false; //是否已有合计标题
			
			//聪明的默认值
			for(int i=0; i<list.size();i++)
			{
				CurdField f = list.get(i);
				f.setCurd(curd);
				
				String fieldType = f.getFieldType();
				String addType = f.getAddType();
				
				//重新设置sn，使其连续
				f.setSn(i+1);
				
				//格式化器
				if(f.getOtherBo() || type_Boolean.equals(fieldType))
				{
					f.setListFormatter("format"+f.getFieldName());
				}
				
				//boolean默认值统一化
				if(type_Boolean.equals(fieldType))
				{
					String defaultValue = f.getDefaultValue();
					if("false".equals(defaultValue) || "0".equals(defaultValue))
					{
						f.setDefaultValue("false");
					}
					else
					{
						f.setDefaultValue("true");
					}
				}
				
				//固定序列显示数据加工
				if(addType_S11.equals(addType) || addType_S21.equals(addType) )
				{
					String parameter = f.getParameter();
					parameter = parameter.replaceAll("，", ","); //中文分隔符替换
					String[] arr = parameter.split(",");
					// [{name: 'closed'}]
					StringBuilder data = new StringBuilder("[");
					for(int k=0;k<arr.length;k++)
					{
						if(k>0)
						{
							data.append(",");
						}
						data.append("{name: '"+arr[k]+"'}");
					}
					data.append("]");
					f.setParameterData(data.toString());
				}

				//只允许有一个合计标题的位置
				if(f.getSumTitle())
				{
					if(haveSumTitle)
					{
						f.setSumTitle(false);
					}
					else
					{
						haveSumTitle = true;
					}
				}
				
			}
			
			curd.setConfigField(true);
			service.saveCurdFieldList(list); //保存配置明细
			
			rm.setMsg("保存成功！");
			rm.setCode(Message._SUCCESS);
		} catch (Exception e) {
			rm.setMsg("保存失败，异常信息：<br/>" + e.toString());
			rm.setCode(Message._ERROR);
			e.printStackTrace();
		}
		return rm;
	}
	

	/**
	 * 根据curdId查询子配置明细
	 */
	@RequestMapping("/findCurdFieldByCurdId")
	@ResponseBody
	public List<CurdField> findCurdFieldByCurdId(Long curdId)
	{
		List<CurdField> boList = service.findCurdFieldByCurdId(curdId);
		for(CurdField bo : boList)
		{
			bo.setCurd(null);
		}
		
		return boList;
	}
	
	/**
	 * 生成测试代码
	 */
	@RequestMapping("/mackCodeTest")
	public String mackCodeTest(Model model, Long id) {
		model.addAttribute("msg", service.mackCode(id,true));
		return this.getPath()+"info";
	}
	
	/**
	 * 删除测试代码
	 */
	@RequestMapping("/deleteTestFile")
	public String deleteTestFile(Model model, Long id) {
		model.addAttribute("msg", service.deleteTestFile(id));
		return this.getPath()+"info";
	}
	
	
	/**
	 * 生成测试代码
	 */
	@RequestMapping("/mackCodeFinal")
	public String mackCodeFinal(Model model, Long id) {
		model.addAttribute("msg", service.mackCode(id,false));
		return this.getPath()+"info";
	}

}
